package org.jeecg.modules.reportLabel.controller;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inOrder1.entity.Bar;
import org.jeecg.modules.outOrder1.entity.OutOrder1;
import org.jeecg.modules.outOrder1.entity.OutOrderZi;
import org.jeecg.modules.outOrder1.service.IOutOrder1Service;
import org.jeecg.modules.outOrder1.service.IOutOrderZiService;
import org.jeecg.modules.reportLabel.entity.OutLabelDTO;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 标签统计报表
 * @Author: jeecg-boot
 * @Date:   2023-12-01
 * @Version: V1.0
 */
@Api(tags="标签统计报表")
@RestController
@RequestMapping("/reportLabel/reportLabel")
@Slf4j
public class ReportLabelController extends JeecgController<ReportLabel, IReportLabelService> {
	@Autowired
	private IReportLabelService reportLabelService;
	@Autowired
	private IOutOrder1Service outOrder1Service;
	@Autowired
	private IOutOrderZiService outOrderZiService;
	
	/**
	 * 分页列表查询
	 *
	 * @param reportLabel
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "标签统计报表-分页列表查询")
	@ApiOperation(value="标签统计报表-分页列表查询", notes="标签统计报表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ReportLabel reportLabel,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String skuCode1 = reportLabel.getSkuCode1();
		String skuCode2 = reportLabel.getSkuCode2();
		reportLabel.setSkuCode1(null).setSkuCode2(null);
		QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (StringUtils.isNotBlank(skuCode1)){
			queryWrapper.like("sku_code1", skuCode1);
		}
		if (StringUtils.isNotBlank(skuCode2)){
			queryWrapper.like("sku_code2", skuCode2);
		}
		queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
		IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 分页列表查询
	  *
	  * @param reportLabel
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "标签统计报表-分页列表查询")
	 @ApiOperation(value="标签统计报表-分页列表查询", notes="标签统计报表-分页列表查询")
	 @GetMapping(value = "/freezeList")
	 public Result<?> freezeList(ReportLabel reportLabel,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 queryWrapper.in("status", 5, 6)
				 .eq("is_freeze", 0);
		 Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
		 IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "标签统计报表-分页列表查询")
	 @ApiOperation(value="标签统计报表-分页列表查询", notes="标签统计报表-分页列表查询")
	 @GetMapping(value = "/thawList")
	 public Result<?> thawList(ReportLabel reportLabel,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								 HttpServletRequest req) {
		 QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 queryWrapper.in("status", 5, 6)
				 .eq("is_freeze", 1);
		 Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
		 IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "标签统计报表-分页列表查询")
	 @ApiOperation(value="标签统计报表-分页列表查询", notes="标签统计报表-分页列表查询")
	 @GetMapping(value = "/lockList")
	 public Result<?> lockList(ReportLabel reportLabel,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 queryWrapper.eq("lock_status", 2);
		 queryWrapper.likeRight("sys_org_code", user.getOrgCode());
		 Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
		 IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  *   冻结
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "标签统计报表-冻结")
	 @ApiOperation(value="标签统计报表-冻结", notes="标签统计报表-冻结")
	 @PostMapping(value = "/isFreeze")
	 public Result<?> isFreeze(@RequestBody List<String> ids) {
		 UpdateWrapper<ReportLabel> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.in("id", ids);
		 updateWrapper.set("is_freeze", 1);
		 reportLabelService.update(updateWrapper);
		 return Result.OK("冻结成功！");
	 }
	 @AutoLog(value = "标签统计报表-解冻")
	 @ApiOperation(value="标签统计报表-解冻", notes="标签统计报表-解冻")
	 @PostMapping(value = "/thaw")
	 public Result<?> thaw(@RequestBody List<String> ids) {
		 UpdateWrapper<ReportLabel> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.in("id", ids);
		 updateWrapper.set("is_freeze", 0);
		 reportLabelService.update(updateWrapper);
		 return Result.OK("解冻成功！");
	 }

	 @GetMapping("/getByBarcode")
	 public Result<?> getByBarcode(@RequestParam(name = "code") String code){
		 ReportLabel reportLabel = reportLabelService.getByCode(code);
		 return Result.OK(reportLabel);
	 }

	 @AutoLog(value = "出库操作-根据出库单id查询标签信息")
	 @ApiOperation(value="出库操作-根据出库单id查询标签信息", notes="出库操作-根据出库单id查询标签信息（叉车司机看到货位）")
	 @GetMapping("/getLabelByOutOrderId")
	 public Result<?> getLabelByOutOrderId(@RequestParam(name = "OutOrderId") String outOrderId){
		 LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(ReportLabel::getOutOrderId, outOrderId);
		 wrapper.eq(ReportLabel::getStatus, 6);
		 List<ReportLabel> labels = reportLabelService.list(wrapper);
		 return Result.OK(labels);
	 }

	 @PostMapping("/unLock")
	 public Result<?> unLock(@RequestBody ReportLabel reportLabel){
		 int lockStatus = reportLabel.getLockStatus();
		 if (lockStatus != 2){
			 return Result.error("货物锁定状态异常，此货物未锁定或已解锁！");
		 }
		 reportLabel.setLockStatus(3);
		 reportLabelService.updateById(reportLabel);
		 return Result.OK("解锁成功！");
	 }

	/**
	 *   添加
	 *
	 * @param reportLabel
	 * @return
	 */
	@AutoLog(value = "标签统计报表-添加")
	@ApiOperation(value="标签统计报表-添加", notes="标签统计报表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ReportLabel reportLabel) {
		reportLabelService.save(reportLabel);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param reportLabel
	 * @return
	 */
	@AutoLog(value = "标签统计报表-编辑")
	@ApiOperation(value="标签统计报表-编辑", notes="标签统计报表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ReportLabel reportLabel) {
		reportLabelService.updateById(reportLabel);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "标签统计报表-通过id删除")
	@ApiOperation(value="标签统计报表-通过id删除", notes="标签统计报表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		reportLabelService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "标签统计报表-批量删除")
	@ApiOperation(value="标签统计报表-批量删除", notes="标签统计报表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.reportLabelService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "标签统计报表-通过id查询")
	@ApiOperation(value="标签统计报表-通过id查询", notes="标签统计报表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ReportLabel reportLabel = reportLabelService.getById(id);
		if(reportLabel==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(reportLabel);
	}

	 @AutoLog(value = "标签统计报表-通过id批量查询")
	 @ApiOperation(value="标签统计报表-通过id批量查询", notes="标签统计报表-通过id批量查询")
	 @GetMapping(value = "/queryByIds")
	 public Result<?> queryByIds(@RequestParam(name="ids",required=true) String ids) {
		 List<Serializable> list = Arrays.asList(ids.split(","));
		 List<ReportLabel> reportLabels = reportLabelService.listByIds(list);
		 return Result.OK(reportLabels);
	 }

	 @AutoLog(value = "标签统计报表-通过出库单id查询")
	 @ApiOperation(value="标签统计报表-通过出库单id查询", notes="标签统计报表-通过出库单id查询")
	 @GetMapping(value = "/queryByOutOrderId")
	 public Result<?> queryByOutOrderId(@RequestParam(name="id",required=true) String id) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ReportLabel::getOutOrderId, id);
		if (user.getUsername().contains("002")){
			wrapper.eq(ReportLabel::getStatus, 8);
		} else if (user.getUsername().contains("003")){
			wrapper.eq(ReportLabel::getStatus, 6);
		}
		List<ReportLabel> labels = reportLabelService.list(wrapper);
		return Result.OK(labels);
	 }

	 @AutoLog(value = "标签统计报表-通过货位码查询")
	 @ApiOperation(value="标签统计报表-通过货位码查询", notes="标签统计报表-通过货位码查询")
	 @GetMapping(value = "/queryByShelfCode")
	 public Result<?> queryByShelfCode(@RequestParam(name="code") String code) {
		 LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(ReportLabel::getCompartmentCode, code);
		 wrapper.eq(ReportLabel::getStatus, 5);
		 List<ReportLabel> labels = reportLabelService.list(wrapper);
		 List<Map<String, Object>> list = new ArrayList<>();
		 Map<String, List<String>> map = new HashMap<>();
		 for (ReportLabel label : labels){
			 String labelNumber = label.getLabelNumber();
			 String split = labelNumber.split("_")[1];
			 String sku = label.getSkuCode1() + " / 剩余 " + label.getActivated() + "件";
			 if (map.containsKey(split)){
				 map.get(split).add(sku);
			 } else {
				 List<String> labelList = new LinkedList<>();
				 labelList.add(sku);
				 map.put(split, labelList);
			 }
		 }
		 for (String key : map.keySet()){
			 Map<String, Object> map1 = new HashMap<>();
			 map1.put("pallet", key);
			 map1.put("sku", map.get(key));
			 list.add(map1);
		 }
		 return Result.OK(list);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param reportLabel
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ReportLabel reportLabel) {
        return super.exportXls(request, reportLabel, ReportLabel.class, "标签统计报表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ReportLabel.class);
    }

	 /**
	  * 通过标签号查询
	  *
	  * @param labelNumber
	  * @return
	  */
	 @AutoLog(value = "标签统计报表-通过标签号查询")
	 @ApiOperation(value="标签统计报表-通过标签号查询", notes="标签统计报表-通过标签号查询")
	 @GetMapping(value = "/queryLabelNumber")
	 public Result<?> queryLabelNumber(@RequestParam(name="labelNumber",required=true) String labelNumber, @RequestParam(name="sign",required=true) Integer sign) {
		 LambdaQueryWrapper<ReportLabel> lqw = Wrappers.lambdaQuery(ReportLabel.class);
		 if (sign==1){
			 lqw.in(ReportLabel::getStatus, "1","2");
		 }
		 lqw.eq(ReportLabel::getLabelNumber, labelNumber);
		 ReportLabel reportLabel = reportLabelService.getOne(lqw);
		 if(reportLabel==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(reportLabel);
	 }

	 /**
	  * 首页--柱形图数据展示在库数据
	  *
	  * @return
	  */
	 @AutoLog(value = "首页--柱形图数据展示在库数据")
	 @ApiOperation(value="首页--柱形图数据展示在库数据", notes="首页--柱形图数据展示在库数据")
	 @GetMapping(value = "/getBar")
	 public Result<?> getBar() {
		 List<Bar> list = reportLabelService.getBar();
		 return Result.OK(list);
	 }

	 @PostMapping("/createOutOrder")
	 public Result<?> createOutOrder(@RequestBody List<OutLabelDTO> list){
		 OutOrder1 outOrder = new OutOrder1();
		 outOrder.setOutOrderStatus(6).setOutOrderType(4).setArea(2).setIsHangUp(0).setOutOrderRules(1)
						 .setOutOrderDate(new Date());
		 outOrder1Service.save(outOrder);
		 OutOrder1 order1 = outOrder1Service.getById(outOrder.getId());
		 List<OutOrderZi> outOrderZis = new LinkedList<>();
		 List<ReportLabel> labels = new LinkedList<>();
		 for (OutLabelDTO label : list){
			 if (5 != label.getStatus() && 14 != label.getStatus()){
				 outOrder1Service.removeById(order1.getId());
				 return Result.error("库存状态错误！货物未上架");
			 }
			 OutOrderZi outOrderZi = new OutOrderZi();
			 outOrderZi.setSkuCode(label.getSkuCode1()).setOutOrderStatus(6).setBoxNum(label.getBoxNum())
					 .setPackagingType(label.getPackagingType()).setTrayNum(1).setPid(order1.getId())
					 .setLabelNumber(label.getLabelNumber()).setOutNum(label.getOutNum())
					 .setActivated(label.getActivated()).setCompartmentCode(label.getCompartmentCode());
			 outOrderZis.add(outOrderZi);
			 ReportLabel reportLabel = new ReportLabel();
			 BeanUtils.copyProperties(label, reportLabel);
			 int activated = reportLabel.getActivated();
			 int newActivated = activated - label.getOutNum();
			 if (newActivated < 0){
				 outOrder1Service.removeById(order1.getId());
				 return Result.error("可用库存不足！");
			 } else {
				 reportLabel.setActivated(newActivated).setStatus(6).setOutOrderId(order1.getId());
				 labels.add(reportLabel);
			 }
		 }
		 reportLabelService.updateBatchById(labels);
		 outOrderZiService.saveBatch(outOrderZis);
		 return Result.OK("操作成功！");
	 }

}
